package com.dps.recommend.config;

import com.dps.recommend.utils.IdGenerate;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Component
@Aspect
public class ControllerAspect {


    @Pointcut("within(@org.springframework.stereotype.Controller *) || within(@org.springframework.web.bind.annotation.RestController *)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object invoke(ProceedingJoinPoint joint) throws Throwable {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String url = request.getServletPath();
            String method = request.getMethod();
            if (!StringUtils.isEmpty(url) && !StringUtils.isEmpty(method)) {
                MDC.put("url", url);
                MDC.put("method", method);
            }
            MDC.put("bizId", IdGenerate.nextId());
            return joint.proceed();
        } finally {
            MDC.remove("url");
            MDC.remove("method");
            MDC.remove("bizId");
        }
    }

}
